// server/sign.js
import OSS from 'ali-oss';
import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());

const sts = new OSS.STS({
  accessKeyId: 'LTAI5tSmJmfqx9x5WiRiu2fC',
  accessKeySecret: 'f7MS99cs60WfT9gpw3t7PiLKdBRNEF'
});

// 生成上传策略
const policy = {
  Version: '1',
  Statement: [{
    Effect: 'Allow',
    Action: [
      'oss:PutObject',
      'oss:GetObject'
    ],
    Resource: [
      'acs:oss:*:*:map-marker-bucket',
      'acs:oss:*:*:map-marker-bucket/*'
    ]
  }]
};

// 获取签名接口
app.get('/api/oss/sign', async (req, res) => {
  try {
    const token = await sts.assumeRole(
      'acs:ram::1740122338848531:role/oss-upload', // RAM角色ARN
      JSON.stringify(policy),
      15 * 60, // 过期时间15分钟
      'web-upload' // 会话名称
    );

    res.json({
      accessKeyId: token.credentials.AccessKeyId,
      accessKeySecret: token.credentials.AccessKeySecret,
      stsToken: token.credentials.SecurityToken,
      expire: token.credentials.Expiration,
      region: 'oss-cn-beijing', // 你的OSS区域
      bucket: 'map-marker-bucket'
    });
  } catch (err) {
    console.error('生成签名失败:', err);
    res.status(500).json({ error: '生成签名失败' });
  }
});

const PORT = 8080;
app.listen(PORT, () => {
  console.log(`签名服务运行在 http://localhost:${PORT}`);
});